package com.tqz.rc.spring.cloud.ribbon.rule;

import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.BaseLoadBalancer;
import com.netflix.loadbalancer.Server;
import com.tqz.rc.api.Instance;
import com.tqz.rc.client.naming.NamingService;
import com.tqz.rc.common.exception.RcException;
import com.tqz.rc.spring.cloud.TqzRcProperties;
import com.tqz.rc.spring.cloud.TqzRcServiceManager;
import com.tqz.rc.spring.cloud.ribbon.TqzRcServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * <p>
 *
 * @author tianqingzhao
 * @since 2021/9/28 17:48
 */
public class TqzWeightedRule extends AbstractLoadBalancerRule {

    Logger log = LoggerFactory.getLogger(TqzWeightedRule.class);

    private TqzRcServiceManager serviceManager;

    private TqzRcProperties properties;

    public TqzWeightedRule(TqzRcServiceManager serviceManager, TqzRcProperties properties) {
        this.serviceManager = serviceManager;
        this.properties = properties;
    }

    @Override
    public void initWithNiwsConfig(IClientConfig clientConfig) {
        // 读取配置文件并初始化，ribbon内部的
    }

    @Override
    public Server choose(Object key) {
        try {
            log.info("key:{}", key);
            BaseLoadBalancer baseLoadBalancer = (BaseLoadBalancer) this.getLoadBalancer();
            log.info("baseLoadBalancer--->:{}", baseLoadBalancer);

            //获取微服务的名称
            String serviceName = baseLoadBalancer.getName();

            //获取Nocas服务发现的相关组件API
            NamingService namingService = serviceManager.getNamingService(properties.getTqzRcProperties());

            //获取 一个基于nacos client 实现权重的负载均衡算法
            Instance instance = namingService.selectOneHealthyInstance(serviceName);

            //返回一个server
            return new TqzRcServer(instance);
        } catch (RcException e) {
            log.error("自定义负载均衡算法错误", e);
        }
        return null;
    }
}
